import { getUserModule, UserModule, getConfig } from '@/services/sys';

import { Rekv } from './rekv';

interface GlobalStore {
  sidebar: UserModule[];
  modules: UserModule[];
  siteConfig: object;
  geetestEnable: boolean;
}

const initState: GlobalStore = {
  sidebar: [],
  modules: [],
  siteConfig: {},
  geetestEnable: false,
};

interface Tree extends UserModule {
  children: UserModule[];
}
function convert(list: UserModule[]) {
  const res = [];
  const map = list.reduce((listItem, v) => {
    // eslint-disable-next-line no-param-reassign
    listItem[v.uri] = v;
    return listItem;
  }, {});
  // eslint-disable-next-line no-restricted-syntax
  for (const item of list) {
    if (item.parentId === '') {
      res.push(item);
      continue; // eslint-disable-line no-continue
    }
    if (item.parentId in map) {
      const parent = map[item.parentId];
      parent.children = parent.children || [];
      parent.children.push(item);
    }
  }
  return res;
}

function treeSort(tree: Tree[]) {
  tree.sort((a, b) => a.sort - b.sort);
  tree.forEach((item) => {
    if (item.children && item.children.length) {
      item.children.sort((a, b) => a.sort - b.sort);
    }
  });

  return tree;
}

/**
 * 用户状态存储
 */
const globalStore = new Rekv({
  initState,
  effects: {
    async getUserModule(store) {
      const res = await getUserModule();

      if (res?.code !== 0) {
        return;
      }
      const { data } = res;

      const sidebar = treeSort(convert(data.filter((bar) => bar.isMenu === 1)));
      store.setState({
        sidebar,
        modules: data,
      });
    },

    async getSite(store) {
      const res: any = await getConfig();
      if (res?.code !== 0) {
        return;
      }
      const { data } = res;
      const listArray: any = data ? data?.list : [];
      const siteConfig = {};
      listArray.forEach((it: any) => {
        siteConfig[it.field] = it.defaultValue;
      });

      store.setState({
        siteConfig,
      });
    },
  },
});

export default globalStore;
